{extend name="main"}
{block name="style"}
<style>
    .hoverable:hover {
        cursor: pointer;
    }

    .covert {
        opacity: 1;
        transition: .5s;
    }

    .hoverable {
        cursor: pointer;
    }

    .optionWrap {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 0px;
        grid-row-gap: 10px;
    }
</style>
{/block}
{block name="body"}
<div class="bg-white mb-3">
    <div class="flex">
        <el-form :model="search" @submit.native.prevent="submitForm" ref="search" label-position="right" class="flex flex-column py-3">
            <div class="flex">
                <el-form-item label="活码名称" class="flex mb-0 pl-3 mr-3">
                    <el-input v-model="search.title" placeholder="输入活码名称以搜索"></el-input>
                </el-form-item>
                <el-form-item label="活码类型" class="flex mb-0 pl-3 mr-3">
                    <el-select>
                        <el-option v-model="search.qr_type" v-for="item in qr_type" :label="item.title" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" class="flex mb-0 pl-3 mr-3">
                    <el-select>
                        <el-option v-model="search.status" v-for="item in status" :label="item.title" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div v-if="moreOption" class="flex mt-3 covert">
                <el-form-item label="创建于" class="flex mb-0 pl-3 mr-3">
                    <el-time-picker is-range v-model="search.create_at" range-separator="-" start-placeholder="开始于" end-placeholder="结束于" placeholder="选择时间段">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="失效于" class="flex mb-0 mr-3">
                    <el-time-picker is-range v-model="search.expired_at" range-separator="-" start-placeholder="开始于" end-placeholder="结束于" placeholder="选择时间段">
                    </el-time-picker>
                </el-form-item>
            </div>

        </el-form>
        <div class="flex pt-2 pb-2 my-2 mh-50px" :class="{'mb-5':moreOption}">
            <el-button type="primary" @click="initHtml()">查询</el-button>
            <el-button plain type="primary" @click="moreOption=!moreOption">{{moreOption?'收起':'更多'}}</el-button>
            <el-button @click="resetForm()">重置</el-button>
        </div>

    </div>
</div>

<div class="bg-white mb-3">
    <div class="table-responsive p-3 flex">
        <!-- 工具条 -->
        <el-button plain type="primary" size="mini" @click="createDialogVisible=true">
            <i class="el-icon-document-add"></i>&nbsp;新建活码
        </el-button>
    </div>
    <div class="table-responsive p-3">
        <el-table ref="tableList" :data="tableData" v-loading="search.requesting" style="width: 100%;">
            <el-table-column label="群活码名称">
                <template slot-scope="scope">
                    <div class="pl-2">{{scope.row.title}}</div>
                </template>
            </el-table-column>
            <el-table-column label="创建时间">
                <template slot-scope="scope">
                    {{scope.row.create_time}}
                </template>
            </el-table-column>
            <el-table-column label="失效时间">
                <template slot-scope="scope">
                    {{scope.row.qr_type==1?'直到主动失效':scope.row.end_time}}
                </template>
            </el-table-column>
            <el-table-column label="活码类型">
                <template slot-scope="scope">
                    <el-tag size="small" :type="scope.row.qr_type==1?'success':'warning'">
                        {{scope.row.qr_type|qrTypeTitle}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-tag size="small" :type="scope.row.status==1?'success':'danger'">{{scope.row.status|statusTitle}}
                    </el-tag>
                    <!-- {{scope.row.qr_type==1?'永久有效':getStatus(scope.row.release_time, scope.row.end_time)}} -->
                </template>
            </el-table-column>
            <el-table-column label="入群人数">
                <template slot-scope="scope">
                    {{scope.row.today_join}}
                </template>
            </el-table-column>
            <el-table-column label="退群人数">
                <template slot-scope="scope">
                    {{scope.row.today_quit}}
                </template>
            </el-table-column>
            <el-table-column label="留存人数">
                <template slot-scope="scope">
                    {{scope.row.all_member}}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="300px">
                <template slot-scope="scope">
                    <div class="optionWrap">
                        <el-button plain @click="option('edit', scope.row)" style="margin-left: 10px" size="mini" type="primary">编辑</el-button>
                        <el-button plain @click="option('spread', scope.row)" size="mini" type="success">推广</el-button>
                        <el-button plain @click="option('invalid', scope.row)" size="mini" type="danger">失效</el-button>
                        <el-button plain @click="option('delete', scope.row)" size="mini" type="danger">删除</el-button>
                        <!-- <el-button plain @click="option('trend', scope.row)" size="mini" type="primary">趋势</el-button> -->
                        <el-button plain @click="option('groups', scope.row)" size="mini" type="primary">群列表</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="table-responsive py-3 text-center">
        <el-pagination background @size-change="sizeChange" @current-change="currentChange" :current-page="search.page" :page-sizes="[10,50,100,200]"
            :page-size="search.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="search.total">
        </el-pagination>
    </div>
</div>

<el-dialog :visible.sync="createDialogVisible">
    <template slot="title">
        <b style="font-size: 16px;">选择活码类型</b>
    </template>
    <div class="flex flex-center flex-v-center">
        <el-card shadow="hover" class="mr-2 hoverable" @click.native="createQR(true)">
            <div class="flex flex-column flex-center flex-v-center h-275px w-275px">
                <div class="mb-3">
                    <el-image fit="cover" src="/static/default1/bsadmin/wechatImg/work_wechat.png"></el-image>
                </div>
                <div class="mb-5"><b>永久码</b>
                    <el-tag size="mini" effect="plain" type="danger">推荐</el-tag>
                </div>
                <div class="dark">
                    基于企微群活码
                </div>
            </div>
        </el-card>
        <el-card shadow="hover" class="ml-2 hoverable" @click.native="createQR(false)">
            <div class="flex flex-column flex-center flex-v-center h-275px w-275px">
                <div class="mb-3">
                    <el-image fit="cover" src="/static/default1/bsadmin/wechatImg/wechat.png"></el-image>
                </div>
                <div class="mb-5"><b>7天码</b></div>
                <div class="dark">
                    7天有效，限时入群
                </div>
            </div>
        </el-card>
    </div>
</el-dialog>

<el-dialog :visible.sync="showGroupsVisible">
    <template slot="title">
        <b style="font-size: 16px;">活码群列表</b>
    </template>
    <el-table if="showGroupsVisible" :data="showQrGroups.groups">
        <el-table-column label="群聊名称" width="200" prop="name">
        </el-table-column>
        <el-table-column label="群主" prop="master">
        </el-table-column>
        <el-table-column label="入群人数" prop="today_join">
        </el-table-column>
        <el-table-column label="退群人数" prop="today_quit">
        </el-table-column>
        <el-table-column label="留存人数" prop="all_member">
        </el-table-column>
        <el-table-column label="操作" width="160">
            <template slot-scope="scope">
                <div class="flex flex-center">
                    <el-button @click="groupInfo(scope.row)" class="p-1" type="primary" size="mini"><i class="el-icon-warning-outline"></i>&nbsp;详情
                    </el-button>
                    <el-button @click="refreshGroup" class="p-1" type="success" size="mini"><i class="el-icon-refresh-left"></i>&nbsp;同步
                    </el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>
</el-dialog>

<el-dialog :visible.sync="showSpreadVisible" width="400px">
    <div style="text-align: center;">
        <canvas ref="qr" width="300" height="300px"></canvas>
    </div>
    <div v-show="false" ref="spreadUrl">{{currentQR.url}}</div>
    <div class="flex flex-v-center">
        <div style="text-align: right; padding-right: 10px;">
            <el-button type="text" @click="downloadQR"><i class="el-icon-download"></i>下载</el-button>
        </div>
        <div style="text-align: left; padding-left: 10px;">
            <el-button id="copyQR" type="text" @click="copyQR"><i class="el-icon-copy-document"></i>复制链接</el-button>
        </div>
    </div>
</el-dialog>
{js href="__PLUGIN_SRC__/QRCode/qrcode.js"}
{js href="__PLUGIN_SRC__/Clipboard/clipboard.min.js"}
{/block}

{block name="script"}
<script type="text/javascript">
    const shareBase = '{:config("web.h5")}'
    const baseView = { view: XYBase.view, /*loading: false*/ }
    const vm = new Vue({
        el: '#app',
        data() {
            return {
                ...baseView,
                createDialogVisible: false,
                showQrGroups: {},
                qr_type: [{ title: '不限', value: 0 }, { title: '7天有效', value: 1 }, { title: '永久码', value: 2 }],
                status: [{ title: '不限', value: 0 }, { title: '有效', value: 1 }, { title: '失效', value: 2 }],
                tableData: [],
                moreOption: false,
                showGroupsVisible: false,
                showSpreadVisible: false,
                currentQR: {},
                search: {
                    page: 1,
                    pageSize: 15,
                    total: 0,
                    title: '',
                    qr_type: null,
                    status: null,
                    requesting: false,
                    created_at: [],
                    expired_at: []
                }
            }
        },
        methods: {
            option(opt, row) {
                let _this = this
                if (opt == 'edit') {
                    // 打开新标签页到
                    const host = location.host
                    window.open(`//${host}/talent/add-alive-qr/${row.id}?qr_type=${row.qr_type}`)
                } else if (opt == 'spread') {
                    _this.showSpreadVisible = true
                    // 生成展示推广码(企微)页面的二维码
                    _this.currentQR.url = shareBase + `/work-wechat/alive-group-qr/${row.id}`
                    _this.currentQR.title = row.title
                    _this.$nextTick(() => {
                        QRCode.toCanvas(
                            _this.$refs['qr'],   /* canvas实例 */
                            _this.currentQR.url,                 /* 二维码中的内容 */
                            { width: 300 },                 /* 二维码相关参数 */
                            function (err) {    /* 回调函数 */
                                // if (err) {
                                //     console.error(err)
                                // }
                            }
                        )
                    })
                } else if (opt == 'invalid') {
                    // 将此活码设为失效
                    $.ajax({
                        url: '/talent/remove_alive_group_qr',
                        type: 'POST',
                        data: JSON.stringify({ id: row.id }),
                        contentType: 'application/json;',
                        success(res) {
                            if (res.code != undefined && res.code == 0) {
                                XYBase.success('已将活码失效')
                                _this.initHtml()
                            }
                        }
                    })
                } else if (opt == 'delete') {
                    // 删除此活码
                    $.ajax({
                        url: 'remove_alive_group_qr',
                        type: 'POST',
                        contentType: 'application/json;',
                        data: JSON.stringify({ id: row.id, force: true }),
                        success(res) {
                            if (res.code != undefined && res.code == 0) {
                                XYBase.success('已将活码删除')
                                _this.initHtml()
                            }
                        }
                    })
                } else if (opt == 'trend') {
                    // 打开趋势页面
                    // 暂时没有这个功能
                } else if (opt == 'groups') {
                    // 展示群列表
                    this.showQrGroups = row
                    this.showGroupsVisible = true
                }
            },
            downloadQR() {
                const a = document.createElement('a');
                a.href = this.$refs['qr'].toDataURL();
                a.setAttribute('download', this.currentQR.title);
                a.click();
            },
            copyQR() {
                const _this = this
                var clip = new ClipboardJS('#copyQR', {
                    // 通过target指定要复印的节点
                    text: function () { return _this.currentQR.url }
                });
                clip.on('success', function (e) {
                    e.clearSelection();
                    XYBase.success('已复制');
                    clip.destroy();
                });
                clip.on('error', function (e) {
                    console.log(e);
                    clip.destroy();
                });
            },
            groupInfo(row) {
                // 跳转到群详情
                window.open(`/talent/detail/${row.id}`)
            },
            refreshGroup() {
                let _this = this
                this.requesting = true
                // 刷新群信息
                $.ajax({
                    url: '/talent/synchronousCustomer',
                    type: 'POST',
                    data: JSON.stringify({ ids: _this.showQrGroups.groups.map(item => item.id) }),
                    contentType: 'application/json;',
                    success(res) {
                        if (res.code != undefined && res.code == 0) {
                            XYBase.success(res.msg)
                            setTimeout(_ => location.reload(), 1500)
                        }
                    }
                })
            },
            createQR(isForever) {
                let baseUrl = window.location.host
                let tagPage = window.open(`//${baseUrl}/talent/add-alive-qr?qr_type=${isForever ? 1 : 0}`)
                console.log(tagPage)
            },
            getStatus(release_time, end_time) {
                let date = new Date()
                if (release_time && end_time) {
                    if (date.getTime() < release_time * 1000 || date.getTime() > release_time * 1000) {
                        return '失效'
                    }
                }
                return '有效'
            },
            currentChange() {

            },
            sizeChange() {

            },
            resetForm() {

            },
            initHtml() {
                let _this = this
                if (this.search.requesting) {
                    return
                }
                this.search.requesting = true
                $.ajax({
                    url: '',
                    type: 'GET',
                    data: _this.search,
                    success(res) {
                        _this.tableData = res.data.data
                        _this.search.total = res.data.total
                    },
                    complete() {
                        _this.search.requesting = false
                    }
                })
            }
        },
        created() {
            this.initHtml()
            XYBase.created(this)
        },
        filters: {
            qrTypeTitle(value) {
                return value == 1 ? '永久码' : '7天码'
            },
            statusTitle(value) {
                return value == 1 ? '有效' : '失效'
            }
        }
    })
</script>
{/block}